package com.tarena.luban.test.repository.impl;

import com.tarena.luban.test.bo.WorkerAreaBO;
import com.tarena.luban.test.dao.WorkerAreaDao;
import com.tarena.luban.test.repository.WorkerAreaRepository;
import com.tarena.luban.test.repository.converter.WorkerAreaConverter;
import com.tarena.tp.luban.worker.po.WorkerArea;
import com.tarena.tp.luban.worker.server.dto.param.WorkerAreaParam;
import com.tarena.tp.luban.worker.server.dto.param.WorkerCreateParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Repository
public class WorkerAreaRepoImpl extends RedisCacheEntry<WorkerAreaBO> implements WorkerAreaRepository {
    @Autowired
    private WorkerAreaDao workerAreaDao;
    @Override
    public void deleteAreas(Long userId) {
        workerAreaDao.delete(userId);
        String key="luban:worker:area:"+userId;
        delete(key);
    }
    @Autowired
    private WorkerAreaConverter workerAreaConverter;
    @Override
    public void saveAreas(WorkerCreateParam workerCreateParam) {
        List<WorkerAreaParam> workerAreaParams = workerCreateParam.getWorkerAreaParams();
        List<WorkerArea> areas=new ArrayList<>();
        //调用转化器方法 循环转化
        for (WorkerAreaParam workerAreaParam : workerAreaParams) {
            WorkerArea workerArea = workerAreaConverter.param2po(workerAreaParam);
            areas.add(workerArea);
        }
        //执行批量新增操作. insert执行一次,数据写入很多条. insert into worker_area (字段) values (第一个元素属性),(第二个元素属性)

        workerAreaDao.insertAreas(areas);
    }
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public List<WorkerAreaBO> findAreas(Long userId) {
        //1.查询缓存判断存在
        String key="luban:worker:area:"+userId;
        List<WorkerAreaBO> workerAreaBOS =null;
        Boolean exists = exists(key);
        if (!exists){
            //1.1 没命中
            List<WorkerArea> areas=workerAreaDao.selectAreasByUserId(userId);
            workerAreaBOS = workerAreaConverter.poList2BoList(areas);
            saveCaches(key,workerAreaBOS,60*60*24l+new Random().nextInt(60*60*5),TimeUnit.SECONDS);
        }else{
            //1.2命中
            workerAreaBOS=getCaches(key);
        }
        return workerAreaBOS;
    }
}
